<!--
mc-col-config:{
              type:
              'checkbox|select|radio|boolean',options:[{k:'',v:''}]}
              type:
                  pk:不可枚举的外键      api:{url:'数据地址' method:'post'|'get' params:[] fields:[]}  pkField:'id' pkTextField:'name'
                  dict:可枚举的数据字典  api:{url:'数据地址' method:'post'|'get' params:[] fields:[]}   pkField:'key' pkTextField:'name'
头样式
thStyle={}
单元格样式
tdStyle={}
TODO:我们封装了vxe-column 取代使用mc-new-vxe-table-column 这使得很多vxe-table的功能有所缺失
  原因：v-bind没法继承
  解决方案：参考:title="title" :field="field" 显示的写出来就能用了
授权配置：rowKey就是角色的key rule:["hide","disabled"]
mc-auth=[{role:"user",rule:"hide"},{role:"test",rule:"disabled"}]
-->

<template>
   <vxe-column :mc-title="title" :mc-edit-rules="mcEditRules" :show-header-overflow="showHeaderOverflow" :show-footer-overflow="showFooterOverflow" :show-overflow="showOverflow" :title="title" :field="field" :width="mcWidth" :min-width="mcMinWidth" v-bind="$attrs" v-on="$listeners">
      <template #header="{column, columnIndex, $columnIndex, _columnIndex, $rowIndex}">
        <span :mc-title="title" class="mc-vxe-table-header-title" :style="thStyle">{{column.title}}</span>
        <!--vxe-table不支持集成排序事件 自定义吧-->
        <span v-if="mcSortable" class="vxe-cell--sort">
          <i title="升序：最低到最高,重复点击则取消排序" :class="ascClass" @click="sortColumn(field,'asc')"></i>
          <i title="降序：最高到最低,重复点击则取消排序" :class="descClass" @click="sortColumn(field,'desc')"></i>
        </span>
      </template>
      <template #default="data">
          <template v-if="mcColConfig && mcColConfig.type=='pk'">
              <el-tag class="mc-cell-pk-el-tag" @click="pkClick(data)" :title="getPkInfo(data).v" v-html="renderText(data)"></el-tag>
              <el-dialog :visible.sync="visibleDialog" width="70%">
                  <!-- 留给父亲渲染插槽 -->
                    <slot name="pk" :pk="pkData"></slot>
              </el-dialog>
          </template>
          <!-- 用户自定义 -->
          <template v-if="mcColConfig && mcColConfig.type=='user'">
              <span v-if="assist.show"  class="mc-list-assist">
                <el-tag class="mc-list-assist-tag" @click="assistClick(1,data)">scope.row</el-tag>
                <el-dialog class="mc-list-assist-dialog" @close="closeDialog"
                           title="设计阶段仅渲染第一条数据，预览页可展开所有数据"
                           :visible.sync="assist.apiVisible"
                           width="80%">
                  <p>以下数据可使用scope.row.xxx来获取数组内的数据</p>
                  <el-input type="textarea" :rows="10" v-model="assist.apiInfo"></el-input>
                  <div>
                    <p>scope.vue.xxx可以调用表格各种方法</p>
                    <p>scope.row.xxx 获取字段</p>
                  </div>
                </el-dialog>
              </span>
              <slot name="row" :row="data.row" :row-index="data.rowIndex" :vue="tableVue" :parent="tableVue.mcParentScope" :loading="tableVue.axiosLoading"></slot>
          </template>
          <!-- 其他类型 -->
          <template v-if="!mcColConfig || (mcColConfig && mcColConfig.type!=='pk' && mcColConfig.type!=='user')">
            <span :style="$el.style.cssText">{{renderText(data)}}</span>
          </template>
      </template>
   </vxe-column>
</template>

<script>
  import McCommon from "./McCommon";
export default {
  name: 'mc-new-vxe-table-column',
  props: ['field','mcColConfig','thStyle','mcSortable','title','formatter','mcEditRules','width','minWidth','showOverflow','showHeaderOverflow','showFooterOverflow'],
  /*如果父模板的edit-type disabled发生变化 就会重绘此组件*/
  computed:{
      ascClass(){
        return this.order=='asc'?'sort--active vxe-sort--asc-btn vxe-icon--caret-top':'vxe-sort--asc-btn vxe-icon--caret-top';
      },
      descClass(){
        return this.order=='desc'?'sort--active vxe-sort--desc-btn vxe-icon--caret-bottom':'vxe-sort--desc-btn vxe-icon--caret-bottom';
      }
  },

  data () {
    return {
        remoteOptions:[],
        pkData:{},
        visible:false,
        visibleDialog:false,
        //指令读取父亲的action
        tableVue:this.$parent.$attrs['mc-table-vue'],
        assist: {show:window.iframeUi,apiVisible:false,apiInfo:""},
        order:"",//排序 asc desc
        // 表格采用了动态渲染如果指定宽 大于总宽 导致右侧不提前渲染字段，设计器就没法给组件列绑定id 所以设计阶段把宽禁用了
        mcWidth:this.width,
        mcMinWidth:this.minWidth
    }
  },
  methods:{
        resetOrder(){
          this.order = "";
        },
        sortColumn(property,order){
            //点击2次就是取消排序
            if(this.order===order){
              this.order="";
            }else {
              this.order = order;
            }
            this.tableVue.sortChange({property,order:this.order});
        },
        assistClick(type,data){
          switch(type){
            case  1:
              var jsonHtml = JSON.stringify(data.row,null,2);
              McCommon.util.parent.layer({title:"一行的数据结构",content:jsonHtml})
              break;
          }
        },
        closeDialog(){

        },
        getPkInfo:function (coldata) {
          if(!this.mcColConfig){
            return {info:null,v:""}
          }
          var type = this.mcColConfig.type;
          if(type!='pk'){
            return {info:null,v:""};
          }
          var pk = coldata.row._mcExtra.pk;
          if(pk && pk[this.field]){
            var v = pk[this.field][this.mcColConfig.pkTextField];
            if(coldata.row._mcExtra&&coldata.row._mcExtra.print){
              coldata.row._mcExtra.print[this.field]=v;
            }
            return {info:pk[this.field],v:v};
          }else{
            return {info:null,v:""};
          }
        },
        renderText: function(coldata){
            var value = coldata.row[this.field]
            if(this.formatter){//这个是函数 用户自定义了格式化数据
              var pkInfo = this.getPkInfo(coldata);
              value = this.formatter({cellValue:value,field:this.field,column:coldata,row:coldata.row,pk:pkInfo});
              //打印的数据
              if(coldata.row._mcExtra && coldata.row._mcExtra.print){
                coldata.row._mcExtra.print[this.field]=value;
              }
              if(coldata.row._mcExtra && coldata.row._mcExtra.titleText){
                coldata.row._mcExtra.titleText[this.title]=value;
              }
              return value;
            }
            if(typeof value!=='undefined' && value!=='' && value!==null && this.mcColConfig){
                  var type = this.mcColConfig.type;
                  switch(type){
                      case 'select':
                      case 'checkbox':
                      case 'radio':
                      case 'boolean':
                      case 'dict':
                          {
                            var options = this.mcColConfig.options || this.remoteOptions;
                            if(options){
                                var kv = {};
                                for(var i=0;i<options.length;i++){
                                    var option = options[i];
                                    var k = option.k;
                                    var v = option.v;
                                    kv[k] = v;
                                }
                                var arr = (value+"").split(",");
                                for(var i=0;i<arr.length;i++){
                                    var k = arr[i];
                                    if(typeof kv[k] != 'undefined'){
                                        arr[i] = kv[k];
                                    }
                                }
                                var v = arr.join(",");
                                if(coldata.row._mcExtra&&coldata.row._mcExtra.print){
                                  coldata.row._mcExtra.print[this.field]=v;
                                }
                                if(coldata.row._mcExtra && coldata.row._mcExtra.titleText){
                                  coldata.row._mcExtra.titleText[this.title]=value;
                                }
                                return v;
                            }
                            break;
                          }
                      case 'pk':
                          {
                            var pk = coldata.row._mcExtra.pk;
                            if(pk && pk[this.field]){
                                var v = pk[this.field][this.mcColConfig.pkTextField];
                                if(coldata.row._mcExtra && coldata.row._mcExtra.print){
                                  coldata.row._mcExtra.print[this.field]=v;
                                }
                                if(coldata.row._mcExtra && coldata.row._mcExtra.titleText){
                                  coldata.row._mcExtra.titleText[this.title]=v;
                                }
                                return v;
                            }else{
                                return "";
                            }
                          }
                  }
            }

            //打印的数据
            if(coldata.row._mcExtra && coldata.row._mcExtra.print){
                coldata.row._mcExtra.print[this.field]=value;
            }
            if(coldata.row._mcExtra && coldata.row._mcExtra.titleText){
                coldata.row._mcExtra.titleText[this.title]=value;
            }
            return value;
        },
        pkClick:function(colData){
            if(true){
              return;
            }
            var rowMcExtra = colData.row._mcExtra;
            var parentObj = rowMcExtra.pk[this.field]
            //还可以展示父亲面板
            this.pkData = parentObj;
            this.visibleDialog = true;
        }
  },
  mounted () {
        var request = this.$magicaltool.request;
        var _t = this;
        if(this.mcColConfig){
            var type = this.mcColConfig.type;
            //字典项 就比较简单 固定的 初始化一次
            if(type == 'dict' && this.mcColConfig.api.url){
                  var url = this.mcColConfig.api.url;
                  var method = this.mcColConfig.api.method||'post';
                  var param = {};
                  if(request.util.isMcQueryUrl(url) || request.util.isContentTypeJson(this.mcColConfig.api.contentType)){
                      param = request.util.paramsTomMcQuery(this.mcColConfig.api.params);
                      if(this.mcColConfig.api.fields && this.mcColConfig.api.fields.length>0){
                          param.fields = this.mcColConfig.api.fields
                      }
                  }else{
                      param = request.util.paramsToJson(this.mcColConfig.api.params)
                  }
                  request.axios({contentType:this.mcColConfig.api.contentType,$vue:this,url:url,method:method,param:param}).then(function(res){
                      var list = res.data;
                      if(list ){
                         var results = [];
                         if(list){
                            for(var n=0;n<list.length;n++){
                                var item = list[n];
                                results.push({k:item[_t.mcColConfig.pkField],v:item[_t.mcColConfig.pkTextField]});
                            }
                         }
                         _t.remoteOptions = results;
                      }
                   })
            }
        }
        //edit-rules
        if(this.mcEditRules){
          var validRules = this.tableVue.getValidRules();
          if(this.field){
            if(this.mcEditRules){
//              console.log(this.mcEditRules)
              for(var i=0;i<this.mcEditRules.length;i++){
                var rule = this.mcEditRules[i];
                if(rule['pattern']){
                  if(rule.pattern.startsWith("/") || rule.pattern.indexOf("RegExp")!=-1){
                    rule.pattern= eval(rule.pattern);//把正则表达式转成正则
                  }else {
                    rule.pattern= new RegExp(rule.pattern);//把正则表达式转成正则
                  }
                }
              }
            }
            validRules[this.field]=this.mcEditRules;
          }
        }
  }
}
</script>

<style lang="scss">
/*行高设置*/
.vxe-table--render-default .vxe-cell {
    white-space: unset !important;
}
.vxe-cell .mc-cell-pk-el-tag{
  width:90%;
  text-overflow: ellipsis;
  overflow: hidden;
}
.mc-vxe-table .col--valid-error>.vxe-cell{
  border: 1px solid #ff0000;
}
</style>
